import React from 'react';
import {
    StyleSheet,
    FlatList,
    View,
    Text,
    ActivityIndicator,
    Image,
    Dimensions
} from 'react-native';

import CommunityHeaderCell from "../cell/CommunityHeaderCell"
import CommunityContentCell from "../cell/CommunityContentCell"
import CommunityTitleCell from "../cell/CommunityTitleCell"
import CommunityMediaGatherCell from "../cell/CommunityMediaGatherCell"
import CommunityMediaCell from "../cell/CommunityMediaCell"
import CommunityToolCell from "../cell/CommunityToolCell"
import CommunityTagCell from '../cell/CommunityTagCell'

import { hot_commentAction } from '../../utils'
import { hot_shareAction } from '../../utils'
import { hot_moreAction } from '../../utils'
import { hot_clickCellAction } from '../../utils'
import { hot_clickImgAction } from '../../utils'

const dataSource = [{
    "id": "1",
    "title": "7年盟主109骨灰级玩家，帮解答...",
    "content": "有任何疑难杂症都可以问！[舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]",
    "needRichText": 0,
    "img": [{ "url": "https://pics3.baidu.com/feed/9d82d158ccbf6c81e987aeece6bf813032fa408c.jpeg?token=5ff799eca4802a8a18a6e9dec912f921&s=7AB531C452F6B5CE0EC71D00030070C8", "width": 378, "height": 310 }],
    "gameName": "眼熟哥哥",
    "time": "5小时前",
    "gameIcon": "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1585564456,2455884638&fm=26&gp=0.jpg",
    "comment": "1509",
    "thumbup": "245",
    "tag": [{ "content": "精华", 'color': 'green' }]
},
{
    "id": "2",
    "title": "2020，我的新年愿望清单",
    "content": "[舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]愿望这东西肯定是张张山水出高[舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]书（属性吸收）、次次洗宠出变异（1技能）、个个装备出特技（卸甲警告）开个玩笑，还是希...",
    "needRichText": 1,
    "img": [{ "url": "https://oss-bbs.2980.com/cb/be/cbbe9dd8984ca4e9f4d0230195e60580-129125-563x427.jpeg?x-oss-process=image/resize,m_1", "width": 563, "height": 427 }],
    "gameName": "mkkkkz",
    "time": "20小时前",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582608379734&di=a96754190d90da150b8e0c0449c67b33&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201703%2F25%2F20170325155121_4RSEx.jpeg",
    "comment": "285",
    "thumbup": "55"
},
{
    "id": "3",
    "title": "2020",
    "content": "有好友嘛[舞蹈][舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]",
    "needRichText": 0,
    "img": [],
    "gameName": "西哈哈哈哈哈",
    "time": "20小时前",
    "gameIcon": "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=872869510,4092430252&fm=26&gp=0.jpg",
    "comment": "892",
    "thumbup": "142"
},
{
    "id": "4",
    "title": "还有一些宝宝懒得弄了，丢家里",
    "content": "[拍手]我是表情[舞蹈][拍手][舞蹈]我是表情[舞蹈][舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]",
    "needRichText": 0,
    "img": [{ "url": "https://image.duoyi.com/com/322/pic/dfb15f21f4a846f5b371458700fdd347.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/ed39518f40bb40dc91ffef23f19275ec.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/57cd9fdf390e4603bdcf60e010540790.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/9127399c730e49a2982dc5a2c280aac8.jpg", "width": 567, "height": 384 }],
    "gameName": "男子汉灬",
    "time": "02-24",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582608020100&di=df0f7083a2e3ec2b592e7bcb96b64da8&imgtype=jpg&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20191230%2F39309aacf6bd48c7b4a78b3d9644cef3.gif",
    "comment": "203",
    "thumbup": "43",
    "tag": [{ "content": "精华", 'color': 'green' }]
},
{
    "id": "5",
    "title": "有没有成都的小哥哥小姐姐[天使]",
    "content": "小白菜，[舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]啥都不会，有没有同[舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]区的朋友加好友，加战友",
    "needRichText": 0,
    "img": [{ "url": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582609234240&di=f42500f78cd3323bfd814d8a4e692755&imgtype=0&src=http%3A%2F%2Fpic2.52pk.com%2Ffiles%2F120606%2F1284620_165254_1_lit.jpg", "width": 317, "height": 400 }],
    "gameName": "小九橙",
    "time": "02-23",
    "gameIcon": "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1636258242,3300857118&fm=26&gp=0.jpg",
    "comment": "473",
    "thumbup": "116",
    "tag": [{ "content": "精华", 'color': 'green' }]
},
{
    "id": "6",
    "title": "没有赶上线下北京站很遗憾",
    "content": "有没有[舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]小姐姐[舞蹈][舞蹈][拍手][拍手][拍手][拍手][舞蹈][舞蹈][舞蹈]求安慰",
    "needRichText": 0,
    "img": [{ "url": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582609517637&di=10d3334f7ea5d719aa3196cd46ffab87&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fbaike%2Fpic%2Fitem%2F023b5bb5c9ea15ce45c20bbcb1003af33a87b253.jpg", "width": 1920, "height": 1280 }],
    "gameName": "shenmadoushi",
    "time": "02-22",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582608736103&di=3e95e4f8fd8fb4bd2f4cf2fcd1de3d45&imgtype=0&src=http%3A%2F%2Fi3.17173cdn.com%2F2fhnvk%2FYWxqaGBf%2Fcms3%2FsbzdDFbllFeEgnf.jpg",
    "comment": "156",
    "thumbup": "210",
    "tag": [{ "content": "精华", 'color': 'green' }]
}
]

export default class CommunityHotView extends React.Component {
    constructor(props) {
        super(props);

        this.canRequest = false

        this.topArr = new Array()

        // var top = {}
        // top.data = tops
        // top.type = 'top'
        // this.topArr.push(top)

        this.contentArr = new Array()
        dataSource.forEach(dict => {
            var header = JSON.parse(JSON.stringify(dict))
            header.type = 'header'
            this.contentArr.push(header)
            var tag = JSON.parse(JSON.stringify(dict))
            tag.type = 'tag'
            this.contentArr.push(tag)
            var title = JSON.parse(JSON.stringify(dict))
            title.type = 'title'
            this.contentArr.push(title)
            var content = JSON.parse(JSON.stringify(dict))
            content.type = 'content'
            this.contentArr.push(content)
            var img = JSON.parse(JSON.stringify(dict))
            img.type = 'img'
            this.contentArr.push(img)
            var tool = JSON.parse(JSON.stringify(dict))
            tool.type = 'tool'
            this.contentArr.push(tool)
        })
        this.dataArr = this.topArr.concat(this.contentArr)
        // console.log('this.dataArr = ' + JSON.stringify(this.dataArr))

        this.contentHeightDict = {}

    }

    state = {
        dataList: this.dataArr,
        isRefresh: false,
        isLoading: true,
        page: 1,
        noData: false,
        hasMorePage: true,
        loadingMore: false,
        listHeight: 0,
        listSize: null
    }

    componentDidMount() {
        this.getShowData(1)
    }

    componentWillUnmount() {
        this.timer && clearTimeout(this.timer)
    }

    render() {
        if (this.state.isLoading) {
            return this.renderLoadingView()
        } else if (this.state.noData && !this.state.isLoading) {
            return this.renderEmptyView()
        } else if (!this.state.noData && !this.state.isLoading) {
            return this.renderMainView()
        }
    }

    renderLoadingView() {
        const { style } = this.props
        return (
            <View style={[styles.loading, style]}>
                <ActivityIndicator
                    animating={true}
                    color='gray'
                    size='large'
                />
            </View>
        )
    }

    renderEmptyView() {
        const { style } = this.props
        return (
            <View style={[styles.listEmpty, style]}>
                <Image style={styles.default_img}
                    source={{ uri: 'http://a3.att.hudong.com/68/61/300000839764127060614318218_950.jpg' }} />
                <Text style={styles.default_content}>未获取到数据</Text>
            </View>
        )
    }

    renderMainView() {
        const { style } = this.props
        return (
            <View style={[styles.container, style]}>
                <FlatList style={styles.flatList}
                    data={this.state.dataList}
                    keyExtractor={this.keyExtractor}
                    renderItem={this.renderItem}
                    // ItemSeparatorComponent={this.renderSeparator}
                    onScroll={this.onScroll}
                    onScrollBeginDrag={this.onScrollBeginDrag}
                    onScrollEndDrag={this.onScrollEndDrag}
                    onMomentumScrollBegin={this.onMomentumScrollBegin}
                    onMomentumScrollEnd={this.onMomentumScrollEnd}
                    refreshing={this.state.isRefresh}
                    onRefresh={this.onRefresh}
                    onEndReached={this.onEndReached}
                    onEndReachedThreshold={0.1}
                    ListFooterComponent={this.renderFooter}
                    contentContainerStyle={{ flexGrow: 1 }}
                    extraData={this.state}
                />
            </View>
        );
    }

    selectSortAction = (item) => {
        // console.log('选中了分类：' + item)
        // this.getShowData(1,'refresh')
    }

    onEndReached = () => {
        // console.log('onEndReached')
        this.requestMoreData()
    }

    requestMoreData = () => {
        // console.log('requestMoreData')
        if (!this.canRequest) return
        if (this.state.page * dataSource.length < this.state.listSize && !this.state.loadingMore) {
            this.setState({
                loadingMore: true
            }, () => {
                this.getShowData(this.state.page)
            })
        } else if (this.state.page * dataSource.length >= this.state.listSize && !this.state.loadingMore) {
            this.setState({
                hasMorePage: false
            })
        }
    }

    renderFooter = () => {
        if (this.state.hasMorePage && this.state.page >= 1) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text style={{ marginLeft: 10 }}>正在加载更多数据...</Text>
                </View>
            )
        } else if (!this.state.hasMorePage && this.state.page >= 1) {
            return (
                <View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
                    <Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, }}>
                        没有更多数据了
                    </Text>
                </View>
            )
        } else {
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            )
        }
    }

    onRefresh = () => {
        this.setState({
            isRefresh: true,
            page: 1
        }, () => {
            this.getShowData(1, 'refresh')
        })
    }

    getShowData(page, type) {
        this.timer = setTimeout(() => {
            if (type === 'refresh') {
                this.setState({
                    dataList: this.dataArr,
                    page: 1,
                    isRefresh: false,
                    isLoading: false,
                    noData: false,
                    loadingMore: false,
                    hasMorePage: true,
                    listSize: 300
                })
            } else {
                this.setState({
                    dataList: this.dataArr.concat(this.state.dataList),
                    page: this.state.page + 1,
                    isRefresh: false,
                    isLoading: false,
                    noData: false,
                    loadingMore: false,
                    listSize: 300
                })
            }
        }, 50)
    }

    // 此函数用于为给定的item生成一个不重复的key
    keyExtractor = (item, index) => '' + index;

    renderItem = ({ item }) => {
        if (item == null) return
        if (item.type == 'header') {
            return (
                <CommunityHeaderCell data={item} moreAction={this.moreAction} clickCellAction={this.clickCellAction} />
            )
        } else if (item.type == 'title') {
            return (
                <CommunityTitleCell data={item} clickCellAction={this.clickCellAction} />
            )
        } else if (item.type == 'content') {
            return (
                <CommunityContentCell data={item} height={this.contentHeight(item)} clickCellAction={this.clickCellAction} cacheHeight={this.cacheContentHeight}/>
            )
        } else if (item.type == 'img' && item.img.length == 1) {
            return (
                <CommunityMediaCell data={item} clickImgAction={this.clickImgAction} />
            )
        } else if (item.type == 'img' && item.img.length > 1) {
            return (
                <CommunityMediaGatherCell data={item} clickImgAction={this.clickImgAction} />
            )
        } else if (item.type == 'tool') {
            return (
                <CommunityToolCell data={item} thumbupAction={this.thumbupAction} shareAction={this.shareAction} commentAction={this.commentAction} />
            )
        } else if (item.type == 'tag' && item.tag && item.tag.length > 0) {
            return (
                <CommunityTagCell data={item} clickCellAction={this.clickCellAction} />
            )
        }
    }

    contentHeight = (item) => {
        let width = Dimensions.get('window').width - 20
        let key = width + item.content
        let height = this.contentHeightDict[key]
        return height
    }

    cacheContentHeight = (key, height) => {
        this.contentHeightDict[key] = height;
    }

    clickImgAction = (item, imgs, radius, idx) => {
        // console.log('hot_clickImgAction')
        hot_clickImgAction(item, imgs, radius, idx)
    }

    moreAction = (item) => {
        // console.log('hot_moreAction')
        hot_moreAction(item)
    }

    clickCellAction = (item) => {
        // console.log('hot_clickCellAction')
        hot_clickCellAction(item)
    }

    shareAction = (item) => {
        // console.log('hot_shareAction')
        hot_shareAction(item)
    }

    commentAction = (item) => {
        // console.log('hot_commentAction')
        hot_commentAction(item)
    }

    thumbupAction = (item) => {

    }

    onScroll = (event) => {
        let offSetY = event.nativeEvent.contentOffset.y
        let contentSizeHeight = event.nativeEvent.contentSize.height
        if (contentSizeHeight - offSetY < 2000) {
            this.requestMoreData()
        }
    }

    onScrollBeginDrag = () => {
        // console.log('onScrollBeginDrag');
        this.canRequest = true;
    }
    onScrollEndDrag = () => {
        // console.log('onScrollEndDrag');
        this.canRequest = false;
    }
    onMomentumScrollBegin = () => {
        // console.log('onMomentumScrollBegin');
        this.canRequest = true;
    }
    onMomentumScrollEnd = () => {
        // console.log('onMomentumScrollEnd');
        this.canRequest = false;
    }
}

const styles = StyleSheet.create({
    safeAreaView: {
        flex: 1
    },
    container: {
        flex: 1,
    },
    sortView: {
        height: 50,
        marginLeft: 0,
        marginRight: 0,
    },
    flatList: {

    },
    separator: {
        height: 0.5,
        marginRight: 0,
        backgroundColor: '#ced0ce',
        marginLeft: 10,
    },
    footer: {
        flexDirection: 'row',
        height: 24,
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 10,
    },
    loading: {
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1,
    },
    listEmpty: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    default_img: {
        width: 90,
        height: 90,
        marginBottom: 20,
        backgroundColor: '#eeeeee'
    },
    default_content: {
        fontFamily: 'PingFangSC-Regular',
        fontSize: 15,
        height: 21,
        color: '#CCCCCC',
        textAlign: 'center'
    }
})